package com.ruantu.clothing.controller;

import com.alibaba.fastjson.JSON;
import com.ruantu.clothing.entity.*;
import com.ruantu.clothing.entity.report.ChuKuReport;
import com.ruantu.clothing.entity.report.Foot;
import com.ruantu.clothing.service.ChuKuService;
import com.ruantu.clothing.util.MyException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/7/9 0009.
 */
@Controller
@RequestMapping("/chuku")
public class ChuKuController {
    private static final Logger logger = LoggerFactory.getLogger(ChuKuController.class);
    @Autowired
    private ChuKuService ckService;



    @RequestMapping("/save")
    @ResponseBody
    public JsonResponseMessage saveChuKu(ChuKu ck, String chukusonString, HttpSession session) {
        /*System.out.print("出库保存:"+ck.getChukuIdArray());*/
        JsonResponseMessage msg = new JsonResponseMessage();
        try {
            User u = (User) session.getAttribute("info");
            ck.setJgId(u.getJgid());
            ck.setZhidanren(u.getId());
            ckService.addChuKu(u, ck, chukusonString);
            msg.setCode(200);
            msg.setMsg("保存成功!");
        } catch (MyException e) {
            e.printStackTrace();
            msg.setCode(400);
            msg.setMsg(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            msg.setCode(400);
            msg.setMsg("数据异常,请联系管理员");
        }
        return msg;

    }

    /***
     * 出库单列表
     * @param ck
     * @param session
     * @return
     */
    @RequestMapping("/chukulist")
    @ResponseBody
    public JsonResponseMessage getChuKuList(ChuKu ck, HttpSession session, PageBean page) {
        JsonResponseMessage msg = new JsonResponseMessage();
        try {
            List<ChuKu> chukuList = ckService.findAllChuKuList(ck, page);
            if (chukuList != null) {
                msg.setCode(200);
                msg.setRows(chukuList);
                msg.setTotal(page.getFoot().getTotal());
                List<Foot> foot =new ArrayList<>();
                foot.add(page.getFoot());
                msg.setFooter(foot);
                msg.setMsg("获取数据成功!");

            } else {
                msg.setCode(1);
                msg.setMsg("暂无数据！");
            }
        } catch (MyException e) {
            e.printStackTrace();
            msg.setCode(400);
            msg.setMsg(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            msg.setCode(400);
            msg.setMsg("数据异常,请联系管理员");
        }
        return msg;

    }

    /***
     * 出库单列表

     * @param session
     * @return
     */
    @RequestMapping("/chukusonlist")
    @ResponseBody
    public JsonResponseMessage getChuKuSonList(String chukuId,int type, HttpSession session) {
        JsonResponseMessage msg = new JsonResponseMessage();
        try {
            List<DanPro> chukuList = ckService.selectAllChuKuSonForCHuKuIdService(chukuId, type);
            if (chukuList != null) {
                msg.setCode(200);
                msg.setData(chukuList);

                msg.setMsg("获取数据成功!");

            } else {
                msg.setCode(1);
                msg.setMsg("暂无数据！");
            }
        } catch (MyException e) {
            e.printStackTrace();
            msg.setCode(400);
            msg.setMsg(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            msg.setCode(400);
            msg.setMsg("数据异常,请联系管理员");
        }
        return msg;

    }


    /***
     * 更改状态出库单

     * @param session
     * @return
     */
    @RequestMapping("/updatechuku")
    @ResponseBody
    public JsonResponseMessage updateChuKuState(Integer state, String beizhu, HttpSession session, String chukuId) {
        JsonResponseMessage msg = new JsonResponseMessage();
        try {
            logger.info("备注信息："+beizhu);
            User u = (User) session.getAttribute("info");
            Integer co = ckService.updateStateService(state, beizhu, u, chukuId);
            if (co != null && co == 0) {
                msg.setCode(200);
                msg.setMsg("状态改变成功!");
            } else {
                msg.setCode(1);
                msg.setMsg("无数据!");
            }
        } catch (MyException e) {
            e.printStackTrace();
            msg.setCode(400);
            msg.setMsg(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            msg.setCode(400);
            msg.setMsg("数据异常,请联系管理员");
        }
        return msg;
    }


    /***
     * 删除单
     * @param session
     * @return
     */
    @RequestMapping("/delchuku")
    @ResponseBody
    public JsonResponseMessage delChuKu(HttpSession session, String chukuId) {
        JsonResponseMessage msg = new JsonResponseMessage();
        try {
            User u = (User) session.getAttribute("info");
            Integer co = ckService.delChuKu(chukuId, u);
            if (co != null && co == 0) {
                msg.setCode(200);
                msg.setMsg("删除成功!");
            } else {
                msg.setCode(1);
                msg.setMsg("删除失败!");
            }
        } catch (MyException e) {
            e.printStackTrace();
            msg.setCode(400);
            msg.setMsg(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            msg.setCode(400);
            msg.setMsg("数据异常,请联系管理员");
        }
        return msg;
    }


    /***
     * 修改出库单
     * @param session
     * @return
     */
    @RequestMapping("/xiuchuku")
    @ResponseBody
    public JsonResponseMessage xiuChuKu(HttpSession session, String chukuId) {
        JsonResponseMessage msg = new JsonResponseMessage();
        try {
            User u = (User) session.getAttribute("info");
            List<ChuKu> xiu = ckService.xiugaiChuKuService(chukuId, u);
            if (xiu != null) {
                msg.setMsg("数据获取成功!");
                msg.setCode(200);
                msg.setData(xiu);
            } else {
                msg.setMsg("暂无数据!");
                msg.setCode(1);
            }
        } catch (MyException e) {
            e.printStackTrace();
            msg.setCode(400);
            msg.setMsg(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            msg.setCode(400);
            msg.setMsg("数据异常,请联系管理员");
        }
        return msg;
    }


    /***
     * 出库
     * @param session
     * @return
     */
    @RequestMapping("/chukux")
    @ResponseBody
    public JsonResponseMessage ChuKu(HttpSession session, String chukuId) {
        JsonResponseMessage msg = new JsonResponseMessage();
        try {
            User u = (User) session.getAttribute("info");
            Integer ck = ckService.ChuKu(u, chukuId);
            if (ck != null && ck == 0) {
                msg.setCode(200);
                msg.setMsg("出库成功！");
            }
        } catch (MyException e) {
            e.printStackTrace();
            msg.setCode(400);
            msg.setMsg(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            msg.setCode(400);
            msg.setMsg("数据异常,请联系管理员!");
        }
        return msg;
    }


    /***
     * 出库退货获得出库单
     * @param session
     * @return
     */
    @RequestMapping("/chukudan")
    @ResponseBody
    public JsonResponseMessage chukudan(HttpSession session, String kehuId,String productId) {
        JsonResponseMessage msg = new JsonResponseMessage();
        try {
            User u = (User) session.getAttribute("info");
            List<ChuKu> chukudanList= ckService.selectChuKuDan(kehuId,productId);
            if (chukudanList != null) {
                msg.setCode(200);
                msg.setData(chukudanList);
                msg.setMsg("获得数据成功!");
            }
        } catch (MyException e) {
            e.printStackTrace();
            msg.setCode(400);
            msg.setMsg(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            msg.setCode(400);
            msg.setMsg("数据异常,请联系管理员");
        }
        return msg;
    }



    @RequestMapping("/savelinghshou")
    @ResponseBody
    public JsonResponseMessage saveLingshou(ChuKu chuKu, String a, HttpSession session) {
        JsonResponseMessage jsonResponseMessage = new JsonResponseMessage();
        User user = (User) session.getAttribute("info");
        try {
            chuKu.setJgId(user.getJgid());
            chuKu.setZhidanren(user.getId());
        } catch (NullPointerException e) {
            jsonResponseMessage.setCode(400);
            jsonResponseMessage.setMsg("服务器连接已断开，请重新登录进行尝试");
            logger.error(e.getMessage());
            return jsonResponseMessage;
        }
        try {
            ckService.saveLingshou(chuKu, a);
            jsonResponseMessage.setCode(200);
            jsonResponseMessage.setData(chuKu.getId());
        } catch (MyException e) {
            logger.error(e.getMessage(), e);
            jsonResponseMessage.setMsg(e.getMessage());
            jsonResponseMessage.setCode(400);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            jsonResponseMessage.setMsg("内部服务器错误，请重新登录进行尝试");
            jsonResponseMessage.setCode(400);
        }
        return jsonResponseMessage;
    }

    @RequestMapping("/sale/list")
    @ResponseBody
    public JsonResponseMessage findSaleList(ChuKu chuKu, String startTime, String endTime, Integer findStyle, PageBean pageBean, HttpSession session) {
        User user = (User) session.getAttribute("info");
        chuKu.setJgId(user.getJgid());
        JsonResponseMessage jsonResponseMessage = new JsonResponseMessage();
        jsonResponseMessage.setRows(ckService.findSaleList(chuKu, startTime, endTime, findStyle, pageBean));
        jsonResponseMessage.setTotal(pageBean.getTotal());
        return jsonResponseMessage;
    }

    @RequestMapping("/sale/id")
    @ResponseBody
    public List<Sale> findSaleId(String id) {

        return ckService.findSaleById(id);
    }

    /**
     * 查询退货
     *
     * @param id
     * @return
     */
    @RequestMapping("/sale/findByChukuid")
    @ResponseBody
    public List<Sale> findTuihuo(String id) {
        return ckService.findTuihuo(id);
    }

    /**
     * 查询退货根据出库id以及商品编号
     *
     * @param sale
     * @return
     */
    @RequestMapping("/sale/findSales")
    @ResponseBody
    public Sale findTuiHuoByProductionDetailsIdWithProductCode(Sale sale) {
        return ckService.findTuiHuoByProductionDetailsIdWithProductCode(sale);
    }

    /**
     * 保存退货单
     *
     * @param
     * @return
     */
    @RequestMapping("/sale/saveTuihuo")
    @ResponseBody
    public JsonResponseMessage saveSaleTuihuo(ChuKu chuKu, String a, String danjuId, HttpSession session) {
        JsonResponseMessage jsonResponseMessage = new JsonResponseMessage();
        User user = (User) session.getAttribute("info");
        try {
            chuKu.setJgId(user.getJgid());
            chuKu.setZhidanren(user.getId());
        } catch (NullPointerException e) {
            jsonResponseMessage.setCode(400);
            jsonResponseMessage.setMsg("服务器连接已断开，请重新登录进行尝试");
            logger.error(e.getMessage());
            return jsonResponseMessage;
        }
        try {
            ckService.saveTuihuo(chuKu, danjuId, a);
            jsonResponseMessage.setCode(200);
        } catch (MyException e) {
            logger.error(e.getMessage(), e);
            jsonResponseMessage.setMsg(e.getMessage());
            jsonResponseMessage.setCode(400);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            jsonResponseMessage.setMsg("内部服务器错误，请重新登录进行尝试");
            jsonResponseMessage.setCode(400);
        }
        return jsonResponseMessage;
    }

    /**
     * 保存退货单
     *
     * @param
     * @return
     */
    @RequestMapping("/sale/findxiaoshou")
    @ResponseBody
    public JsonResponseMessage findXiaoshou(HttpSession session) {
        JsonResponseMessage jsonResponseMessage = new JsonResponseMessage();
        User user = (User) session.getAttribute("info");
        try {
            jsonResponseMessage.setCode(200);
            jsonResponseMessage.setData(ckService.findXiaoshou(user));
        } catch (MyException e) {
            logger.error(e.getMessage(), e);
            jsonResponseMessage.setMsg(e.getMessage());
            jsonResponseMessage.setCode(400);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            jsonResponseMessage.setMsg(e.getMessage());
            jsonResponseMessage.setCode(400);
        }
        return jsonResponseMessage;
    }

    /**
     * 小票打印查询
     *
     * @param id
     * @return
     */
    @RequestMapping("/salexiaopiao")
    @ResponseBody
    public JsonResponseMessage findSaleXiaopiao(String id) {
        JsonResponseMessage jsonResponseMessage = new JsonResponseMessage();
        try {
            jsonResponseMessage.setData(ckService.findSaleXiaopiao(id));
            jsonResponseMessage.setCode(200);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            jsonResponseMessage.setMsg("服务器内部错误，请刷新重新尝试");
            jsonResponseMessage.setCode(400);
        }
        return jsonResponseMessage;
    }



    /***
     * 出库
     * @param session
     * @return
     */
    @RequestMapping("/findYearAndSeason")
    @ResponseBody
    public JsonResponseMessage findYearAndSeason(HttpSession session, String chukuId) {
        JsonResponseMessage msg = new JsonResponseMessage();
        try {
            User u = (User) session.getAttribute("info");
            List<YearAndSeason> yearandseason = ckService.selectYearAndSeasaonSevice();
            if (yearandseason!=null) {
                msg.setCode(200);
                msg.setMsg("获取数据成功！");
                msg.setData(yearandseason);
            }
        } catch (MyException e) {
            e.printStackTrace();
            msg.setCode(400);
            msg.setMsg(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            msg.setCode(400);
            msg.setMsg("数据异常,请联系管理员!");
        }
        return msg;
    }

    /***
     * 出库报表
     */
    @RequestMapping("/findChuKuReport")
    @ResponseBody
    public JsonResponseMessage findChuKuReport(PageBean page) {
        JsonResponseMessage msg = new JsonResponseMessage();
        try {

            List<ChuKuReport> ChuKuReportList = ckService.selectChuKuReportList(page);
            if (ChuKuReportList!=null) {
                msg.setCode(200);
                msg.setMsg("获取数据成功！");
                msg.setRows(ChuKuReportList);
                msg.setTotal(page.getFoot().getTotal());
                List<Foot> foot=new ArrayList<>();
                foot.add(page.getFoot());
                msg.setFooter(foot);
            }
        } catch (MyException e) {
            e.printStackTrace();
            msg.setCode(400);
            msg.setMsg(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            msg.setCode(400);
            msg.setMsg("数据异常,请联系管理员!");
        }
        return msg;
    }


    /****
     * 销售报表导出
     * @param session
     * @param page
     * @param out
     * @return
     */
    @RequestMapping("/sale_report")
    @ResponseBody
    public ResponseEntity<byte[]> ZongHZhangDaoChuMX(HttpSession session, PageBean page, ServletOutputStream out) {
        JsonResponseMessage msg = new JsonResponseMessage();
        try {
            User user = (User) session.getAttribute("info");
            HSSFWorkbook wb = ckService.selectChuKuReportListDaoChu(page);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
            wb.write(out);
            outByteStream.flush();
            outByteStream.close();
            return new ResponseEntity<byte[]>(outByteStream.toByteArray(), headers, HttpStatus.OK);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }




}
